package com.powernode.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powernode.domain.SysLoginUser;
import com.powernode.domain.WxUser;
import com.powernode.mapper.SysUserMapper;
import com.powernode.service.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private WxUserService wxUserService;
    //得到配置文件中 weix appid url secret
    @Value("${Wx.appId}")
    private String appId;
    @Value("${Wx.secret}")
    private String secret;
    @Value("${Wx.url}")
    private String url;

    /**
     * 对用户进行判断，是哪种用户登录
     * sysUser  系统用户  member  小程序用户
     * 通过设置请求头 loginType 来判断
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String loginType = request.getHeader("loginType");
        UserDetails userDetails = null;
        //对请求头进行判断
        switch (loginType) {
            //获得为系统用户的账户
            case "sysUser":
                SysLoginUser sysLoginUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysLoginUser>().eq(SysLoginUser::getUsername, username));
                if (!ObjectUtils.isEmpty(sysLoginUser)) {
                    List<String> auths = sysUserMapper.selectAuthsByUserId(sysLoginUser.getUserId());
                    sysLoginUser.setAuths(auths);
                }
                userDetails = sysLoginUser;
                break;
            case "member":
                //url 使用了 %s 占位 将其获得
                //此时的usernname 就是code
              String  urlstr = String.format(url, appId, secret, username);
                //使用hutool工具发送请求
                //得到信息
                String str = HttpUtil.get(urlstr);
                JSONObject jsonObject = JSON.parseObject(str);
                //得到 用户唯一标识 此标识对应数据库userid
                String userId = jsonObject.getString("openid");
                //根据用户id查询数据库
                //如果查询到数据 则直接登录
                //如果没查询到用户 则添加 进行注册
                if (StringUtils.hasText(userId)) {
                    WxUser wxUser = wxUserService.getById(userId);
                    if (ObjectUtils.isEmpty(wxUser)) {
                        creatWxUser(wxUser, userId);
                    }
                    userDetails = wxUser;
                }
                break;

        }
        return userDetails;
    }

    public WxUser creatWxUser(WxUser wxUser, String userId) {
        wxUser = new WxUser();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteHost();
        wxUser.setUserId(userId);
        wxUser.setModifyTime(new Date());
        wxUser.setUserRegtime(new Date());
        //注册ip必须设置 否则无法认证成功
        wxUser.setUserRegip(ip);
        wxUser.setUserLastip(ip);
        wxUserService.save(wxUser);
        return wxUser;
    }
}
